<template>
  <c-form-dialog
    label-width="140px"
    :title="tableId ? '修改项目信息' : '新增项目信息'"
    ref="form"
    class="project-new-form"
    :table-name="formTable"
    :form-items="formItems"
    :form-data="formData"
    :before-save="handleBeforeSave"
    :table-id="tableId"
    :submit="submit"
    :visible.sync="innerVisible"
    @close="handleDismiss"
    :auto-close="false"
    v-on="$listeners"
    :v-loading="loading"
  >
    <span class="validate-result ml-3" slot="appendSlot">
      <i class="fa fa-check text-success"></i>
      <i class="fa fa-times text-danger"></i>
    </span>
  </c-form-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { idCardValidate, license18Validate } from '@vimi/utils-tool'

import { mobileValidator } from '@/common/plugins/validator'
import { enumDispute } from '@/bank/plugins/enum'

import { dateFormat } from '@/common/utils/common'
import SelectParentMain from '@/bank/views/limit/SelectParentMain'
import SelectFundsUser from '@/bank/views/limit/SelectFundsUser'
import SelectCustomerType from '@/bank/views/limit/SelectCustomerType'
const useType = [{ label: '固定资产贷款' }, { label: '流动资金贷款' }]
export default {
  components: {},
  props: {
    visible: Boolean,
    tableId: String,
    submit: { type: Boolean, default: true },
    formData: { type: Object, default: () => ({}) },
    isBackData: { type: Boolean, default: false },
  },
  data() {
    const idCardValidator = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!idCardValidate(value)) {
        callback(new Error('错误的身份证号，请重新输入'))
      } else {
        callback()
      }
    }
    const registerNoValidator = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!license18Validate(value)) {
        callback(new Error('错误的统一信用代码，请重新输入'))
      } else {
        callback()
      }
    }
    const rateValidator = (rule, value, callback) => {
      // 2022-12-28 石勇
      if (!value) {
        callback()
      } else if (!Number.isFinite(+value)) {
        callback(new Error('请输入正确的数值'))
      } else {
        callback()
      }
    }
    const isNumberValidator = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!Number.isFinite(+value)) {
        callback(new Error('请输入正确的数值'))
      } else {
        callback()
      }
    }
    const fundsValidator = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!Number.isFinite(+value)) {
        callback(new Error('请输入正确的数值'))
      } else if (+value <= 0) {
        callback(new Error('金额应大于0'))
      } else {
        callback()
      }
    }
    const businessValidator = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!this.provinceMainBusinessEnum[value]) {
        callback(new Error('十二大产业分类不匹配'))
      } else {
        callback()
      }
    }

    const parentBusinessValidator = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!this.selectArray.find(item => item.code === value)) {
        callback(new Error('行业类型不匹配'))
      } else {
        callback()
      }
    }

    const empValidator = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (+value < 0 || value % 1 !== 0) {
        callback(new Error('人数需填写正整数'))
      } else {
        callback()
      }
    }

    const comNumberValidator = (rule, value, callback) => {
      if (+value <= 0) {
        callback(new Error('企业用户，填写值需大于0'))
      } else {
        callback()
      }
    }

    const periodValidator = (rule, value, callback) => {
      if (!value && value !== 0) {
        callback()
      } else if (+value > 60) {
        callback(new Error('贷款期限不能大于60个月'))
      } else {
        callback()
      }
    }

    const useTypeValidator = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!useType.find(item => item.label === value)) {
        callback(new Error('贷款具体用途和所属行业不匹配'))
      } else {
        callback()
      }
    }

    const fundsUserDirValidator = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (value === '其他' || value === '其它') {
        callback(new Error('请输入具体用途'))
      } else {
        callback()
      }
    }
    return {
      formTable: 'datum_one_county_industry',
      innerVisible: false,
      registerList: [],
      idImgFront: [],
      idImgBack: [],
      formItems: [
        {
          tag: 'input',
          itemAttrs: {
            label: '放款银行名称',
            rules: [{ required: true, message: '请输入放款银行名称', trigger: 'blur' }],
          },
          attrs: { key: 'claim_bank_name', value: '', placeholder: '请输入放款银行名称' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          attrs: { key: 'address_name_county' },
          ifShow: false,
        },
        {
          tag: SelectCustomerType,
          itemAttrs: {
            label: '客户类型',
            rules: { required: true, message: '请选择客户类型', trigger: 'change' },
          },
          attrs: { clearable: false, key: 'org_class', class: 'form-control-ml' },
          appendSlot: 'appendSlot',
          events: {
            select: (model, v, label) => {
              this.orgClass = v || ''
              model.org_class_name = label || ''
            },
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '客户名称',
            rules: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
          },
          attrs: { key: 'customer_name', value: '', placeholder: '请输入客户名称' },
          appendSlot: 'appendSlot',
          events: {
            change: mode => this.getCustomerName(mode),
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '法定代表人或实际控制人',
            rules: { required: true, message: '请输入法定代表人或实际控制人', trigger: 'blur' },
          },
          attrs: { key: 'corp_name', value: '', placeholder: '法定代表人或实际控制人' },
          appendSlot: 'appendSlot',
          ifRender: () => this.isCommon,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '身份证号码',
            rules: {
              rules: {
                validator: idCardValidator,
                message: '请输入正确的身份证号码',
                trigger: 'blur',
              },
            },
          },
          attrs: { key: 'lender_idcard', value: '', placeholder: '请输入信息' },
          appendSlot: 'appendSlot',
          events: {
            change: mode => this.getCustomerName(mode),
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '身份证证件地址',
          },
          attrs: { key: 'cert_address_corp', value: '', placeholder: '身份证证件地址' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '联系电话',
          },
          attrs: { key: 'corp_phone', value: '', placeholder: '联系电话' },
          appendSlot: 'appendSlot',
          getItemAttrs: model => {
            return {
              rules:
                +model.is_cert_merge === 0
                  ? { validator: mobileValidator, message: '请输入正确的手机号码', trigger: 'blur' }
                  : [
                      { required: true, message: '请输入手机号码', trigger: 'blur' },
                      {
                        validator: mobileValidator,
                        message: '请输入正确的手机号码',
                        trigger: 'blur',
                      },
                    ],
            }
          },
        },
        {
          tag: 'radio-group',
          itemAttrs: { label: '三证合一' },
          attrs: { clearable: false, key: 'is_cert_merge', value: '0', options: enumDispute },
          appendSlot: 'appendSlot',
          ifRender: () => this.isCommon,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '统一社会信用代码',
            rules: [
              {
                required: true,
                message: '三证合一、农业企业、农民专业合作社必填',
                trigger: 'blur',
              },
              {
                validator: registerNoValidator,
                message: '请输入正确的统一社会信用代码',
                trigger: 'blur',
              },
            ],
          },
          attrs: { key: 'register_no', value: '', placeholder: '请输入信息' },
          appendSlot: 'appendSlot',
          events: {
            change: mode => this.getCustomerName(mode),
          },
          ifRender: model => +model.is_cert_merge === 1 || this.isCommon,
        },
        {
          tag: SelectParentMain,
          itemAttrs: {
            label: '所属行业',
            rules: [
              { required: true, message: '请选择所属行业', trigger: 'change' },
              { validator: parentBusinessValidator, trigger: 'change' },
            ],
          },
          attrs: { clearable: false, key: 'industrial_code', class: 'form-control-ml' },
          appendSlot: 'appendSlot',
          events: {
            select: (model, value, select) => {
              // model.use_category = ''
              const fundsUser = this.fundsUser.find(item => item.code === model.use_category)
              if (!fundsUser || (value && fundsUser.parentId !== value)) {
                model.use_category = model.funds_use_dir
              }
              this.$refs.form.validateField('use_category')
              model.parent_main_business = select.value || ''
              model.main_business_code = select.productTypeCode || ''
            },
          },
        },
        {
          tag: SelectFundsUser,
          itemAttrs: {
            label: '贷款具体用途',
          },
          attrs: {
            key: 'use_category',
            placeholder: '请选择贷款具体用途',
            class: 'form-control-ml',
          },
          appendSlot: 'appendSlot',
          getAttrs: model => {
            return { parentId: model.industrial_code }
          },
          getItemAttrs: model => {
            const fundsUserValidator = (rule, value, callback) => {
              const fundsUser = this.fundsUser.find(item => item.code === value)
              if (!value) {
                callback()
              } else if (
                !fundsUser ||
                (model.industrial_code && fundsUser.parentId !== model.industrial_code)
              ) {
                callback(new Error('贷款用途不匹配'))
              } else {
                callback()
              }
            }
            return {
              rules: [
                { required: true, message: '请选择贷款用途', trigger: 'change' },
                { validator: fundsUserValidator, trigger: 'change' },
              ],
            }
          },
          events: {
            change: () => {
              this.$refs.form.validateField('use_category')
            },
            select: (model, select) => {
              model.funds_use_dir = select.value || ''
              model.main_business_code = select.productTypeCode || model.main_business_code
            },
          },
        },
        {
          tag: 'input',
          attrs: {
            key: 'funds_use_dir',
          },
          ifShow: false,
        },
        {
          tag: 'input',
          attrs: {
            key: 'parent_main_business',
          },
          ifShow: false,
        },
        {
          tag: 'select',
          itemAttrs: {
            label: '十二大产业',
            rules: [
              { required: true, message: '请选择十二大产业', trigger: 'change' },
              { validator: businessValidator, trigger: 'change' },
            ],
          },
          attrs: {
            clearable: false,
            key: 'main_business_code',
            disabled: true,
            placeholder: '请选择十二大产业',
          },
          appendSlot: 'appendSlot',
          getAttrs: () => {
            return { options: this.provinceMainBusinessEnum }
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '担保(放款)金额',
            rules: [
              { required: true, message: '请输入担保(放款)金额', trigger: 'blur' },
              { validator: fundsValidator, trigger: 'blur' },
            ],
          },
          attrs: { key: 'warranty_amount', value: '' },
          tagSlots: [{ name: 'append', slot: '万元' }],
          appendSlot: 'appendSlot',
        },
        {
          tag: 'date',
          itemAttrs: {
            label: '放款日期',
          },
          attrs: { key: 'load_date', value: '', placeholder: '请选择放款日' },
          appendSlot: 'appendSlot',
          getItemAttrs: model => {
            const loadValidator = (rule, value, callback) => {
              if (!value || !model.load_end_date) {
                callback()
              } else if (value > model.load_end_date) {
                callback(new Error('放款日期不能大于还款日期'))
              } else {
                callback()
              }
            }
            model.warranty_period = this.countMonth(model.load_date, model.load_end_date)
            return {
              rules: [
                { required: true, message: '请选择放款日', trigger: 'change' },
                { validator: loadValidator, trigger: 'change' },
              ],
            }
          },
          events: {
            change: () => {
              this.$refs.form.validateField('warranty_period')
              this.$refs.form.validateField('load_rate')
            },
          },
        },
        {
          tag: 'date',
          itemAttrs: {
            label: '还款日期',
            rules: [{ required: true, message: '还款日期', trigger: 'change' }],
          },
          appendSlot: 'appendSlot',
          attrs: { key: 'load_end_date', value: '', placeholder: '请选择还款日期' },
          getItemAttrs: model => {
            const loadValidator = (rule, value, callback) => {
              if (!value || !model.load_date) {
                callback()
              } else if (model.load_date > value) {
                callback(new Error('还款日期不能小于放款日期'))
              } else if (value < dateFormat(new Date())) {
                callback(new Error('还款日期不能小于当前日期'))
              } else {
                callback()
              }
            }
            model.warranty_period = this.countMonth(model.load_date, model.load_end_date)
            return {
              rules: [
                { required: true, message: '请选择放款日', trigger: 'change' },
                { validator: loadValidator, trigger: 'change' },
              ],
            }
          },
          events: {
            change: () => {
              this.$refs.form.validateField('warranty_period')
              this.$refs.form.validateField('load_rate')
            },
          },
        },
        {
          tag: 'number',
          itemAttrs: {
            label: '贷款期限',
            rules: [
              { required: true, message: '请输入贷款期限', trigger: 'blur' },
              { validator: periodValidator, trigger: 'blur' },
            ],
          },
          attrs: {
            key: 'warranty_period',
            value: '',
            placeholder: '请输入贷款期限',
          },
          tagSlots: [{ name: 'append', slot: '月' }],
          appendSlot: 'appendSlot',
        },
        {
          tag: 'select',
          itemAttrs: {
            label: '贷款用途分类',
            rules: [
              { required: true, message: '请选择贷款用途分类', trigger: 'change' },
              { validator: useTypeValidator, trigger: 'change' },
            ],
          },
          attrs: {
            key: 'use_category_name',
            value: '',
            props: { value: 'label', label: 'label' },
            options: useType,
          },
        },

        {
          tag: 'input',
          itemAttrs: {
            label: '借款合同号/授信号',
          },
          attrs: { key: 'gua_contract', value: '', placeholder: '请输入借款合同号' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '借据号',
            rules: [{ validator: this.guaContractValidator, trigger: 'blur' }],
          },
          attrs: { key: 'iou_no', value: '', placeholder: '请输入借据号' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '贷款利率',
            rules: [{ validator: rateValidator, trigger: 'blur' }],
          },
          attrs: { key: 'load_rate', value: '', placeholder: '请输入贷款利率' },
          tagSlots: [{ name: 'append', slot: '%' }],
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '销售收入',
            rules: [
              { required: true, message: '请输入销售收入', trigger: 'blur' },
              { validator: isNumberValidator, trigger: 'blur' },
            ],
          },
          attrs: { key: 'sale_income', value: '', placeholder: '请输入销售收入' },
          tagSlots: [{ name: 'append', slot: '万元' }],
          appendSlot: 'appendSlot',
          getItemAttrs: () => {
            return this.isCommon
              ? {
                  rules: [
                    { required: true, message: '请输入销售收入', trigger: 'blur' },
                    { validator: isNumberValidator, trigger: 'blur' },
                    { validator: comNumberValidator, trigger: 'blur' },
                  ],
                }
              : {
                  rules: [
                    // { required: true, message: '请输入销售收入，如无请填0', trigger: 'blur' },
                    { validator: isNumberValidator, trigger: 'blur' },
                  ],
                }
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '资产总额',
            rules: [
              { required: true, message: '请输入资产总额', trigger: 'blur' },
              { validator: isNumberValidator, trigger: 'blur' },
            ],
          },
          attrs: { key: 'assets_total', value: '', placeholder: '请输入资产总额' },
          tagSlots: [{ name: 'append', slot: '万元' }],
          appendSlot: 'appendSlot',
          getItemAttrs: () => {
            return this.isCommon
              ? {
                  rules: [
                    { required: true, message: '请输入资产总额', trigger: 'blur' },
                    { validator: isNumberValidator, trigger: 'blur' },
                    { validator: comNumberValidator, trigger: 'blur' },
                  ],
                }
              : {
                  rules: [
                    // { required: true, message: '请输入资产总额，如无请填0', trigger: 'blur' },
                    { validator: isNumberValidator, trigger: 'blur' },
                  ],
                }
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '从业人数',
            rules: [
              { required: true, message: '请输入从业人数', trigger: 'blur' },
              { validator: isNumberValidator, trigger: 'blur' },
              { validator: empValidator, trigger: 'blur' },
            ],
          },
          attrs: { key: 'emp_total', value: '', placeholder: '请输入从业人数' },
          tagSlots: [{ name: 'append', slot: '人' }],
          appendSlot: 'appendSlot',
          getItemAttrs: () => {
            return this.isCommon
              ? {
                  rules: [
                    { required: true, message: '请输入从业人数', trigger: 'blur' },
                    { validator: isNumberValidator, trigger: 'blur' },
                    { validator: empValidator, trigger: 'blur' },
                    { validator: comNumberValidator, trigger: 'blur' },
                  ],
                }
              : {
                  rules: [
                    // { required: true, message: '请输入从业人数，如无请填0', trigger: 'blur' },
                    { validator: isNumberValidator, trigger: 'blur' },
                    { validator: empValidator, trigger: 'blur' },
                  ],
                }
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '收取其他费用',
            rules: [{ validator: isNumberValidator, trigger: 'blur' }],
          },
          attrs: { key: 'other_cost', value: '', placeholder: '请输入收取其他费用' },
          tagSlots: [{ name: 'append', slot: '元' }],
          appendSlot: 'appendSlot',
        },
        {
          tag: 'textarea',
          itemAttrs: { label: '备注', rules: {} },
          attrs: { key: 'remark', value: '', placeholder: '请输入备注', autosize: { minRows: 3 } },
          getItemAttrs: model => {
            if (!model.funds_use_dir) {
              return
            }
            return model.funds_use_dir === '其他' || model.funds_use_dir === '其它'
              ? {
                  rules: [
                    { required: true, message: '请输入贷款具体用途', trigger: 'blur' },
                    { validator: fundsUserDirValidator, trigger: 'blur' },
                  ],
                }
              : {}
          },
        },
      ],
      cityCode: '',
      orgClass: '',
      editData: {},
      imgData: [],
      loading: false,
      month: 0,
    }
  },
  computed: {
    ...mapGetters([
      'clientId',
      'org',
      'user',
      'userId',
      'provinceMainBusinessEnum',
      'industryType',
      // 'accessData',
    ]),
    queryAddressCode() {
      return this.user.queryAddressCode
    },
    selectArray() {
      return this.industryType.filter(item => +item.type < 3)
    },
    fundsUser() {
      return this.industryType.filter(item => +item.type === 3)
    },
    isProvince() {
      return +this.user.orgRegionLever === 1
    },
    isCounty() {
      return +this.user.orgRegionLever > 2
    },

    isCommon() {
      return ['org_cooperative', 'org_enterprise'].includes(this.orgClass)
    },
    dir() {
      return `/bank/newProjec/limit/${this.clientId}`
    },
  },
  watch: {
    visible(val) {
      this.innerVisible = val
      this.orgClass = this.formData.org_class
      this.month = this.formData.warranty_period || 0

      const fundsUser = this.fundsUser.find(item => item.code === this.formData.use_category)
      if (
        !fundsUser ||
        (this.formData.industrial_code && fundsUser.parentId !== this.formData.industrial_code)
      ) {
        this.formData.use_category = this.formData.funds_use_dir
      }
      if (
        !this.formData.main_business_code ||
        !this.provinceMainBusinessEnum[this.formData.main_business_code]
      ) {
        this.formData.main_business_code = this.formData.main_business
      }

      if (val && this.tableId) {
        this.toValidate()
      }
    },
  },
  created() {
    this.$store.dispatch('getProvinceMainBusiness')
    this.$store.dispatch('getIndustryType')
    // this.$store.dispatch('getAccessData')
  },
  mounted() {},
  methods: {
    getCustomerName(mode) {
      if (!mode.customer_name) {
        return
      }
      if (this.isCommon && !mode.register_no) {
        return
      }
      if (!this.isCommon && !mode.lender_idcard) {
        return
      }
      const params = this.isCommon
        ? {
            'register_no.eq': mode.register_no,
            'customer_type.eq': 1,
          }
        : { 'lender_idcard.eq': mode.lender_idcard, 'customer_type.eq': 2 }
      return this.$api
        .getData(this.$serviceName, 'datum_one_county_industry', {
          ...params,
          groupFields: 'customer_name',
          'customer_related_id.neq': this.tableId || '',
        })
        .then(res => {
          const data = (res?.data ?? []).map(item => item.customer_name)
          const str = data.join('、')
          if (data.length > 0 && !data.includes(mode.customer_name)) {
            this.$alert(`此证件号对应多个名称: ${str}`, '提示', {
              confirmButtonText: '确定',
              type: 'warning',
            })
          }
        })
    },

    async onSubmit() {
      if (this.tableId) {
        await this.$api
          .updateData(this.$serviceName, this.formTable, this.tableId, this.editData)
          .then(() => {
            this.$message.success('修改成功！')
            this.handleDismiss()
            this.$emit('success', true)
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    countMonth(start, end) {
      let month = 0
      if (start && end) {
        const startData = new Date(start)
        const endData = new Date(end)
        const startYear = startData.getFullYear()
        const endYear = endData.getFullYear()
        const startMonth = startData.getMonth() + 1
        const endMonth = endData.getMonth() + 1
        const startDay = startData.getDate()
        const endDay = endData.getDate()
        month = (endYear - startYear) * 12 + (endMonth - startMonth)
        if (month < 6) {
          month -= endDay >= startDay ? 0 : 1
        } else {
          month += endDay > startDay + 5 ? 1 : 0
        }
      }
      if (month === 5) {
        month = 6
      }
      this.month = month
      return month
    },
    warrantyAmountAsyncValidator(model) {
      if (!model.lender_idcard && !model.register_no) {
        return Promise.resolve({})
      }

      return this.$http.get(
        `/api/gua/customer-left-funds-view-total/statistics/?isBIQuery=1&apiKey=left-funds-total&customerRelatedID=${
          this.tableId
        }&certNo=${this.isCommon ? model.register_no : model.lender_idcard}`
      )
    },
    guaContractValidator(rule, value, callback) {
      if (!value) {
        callback()
      } else {
        this.$api
          .getData(this.$serviceName, this.formTable, {
            index: 1,
            size: 1,
            'customer_related_id.neq': this.tableId || '',
            'review_approval.neq': 3,
            fields: ['iou_no', 'bank_name'],
            'iou_no.eq': value,
          })
          .then(res => {
            const data = res?.data?.data || []

            if (data.length) {
              callback(new Error(`借据号重复, 已导入`))
            } else {
              callback()
            }
          })
          .catch(() => {
            callback()
          })
      }
    },
    toValidate() {
      this.$nextTick(() => {
        const cfrom = this.$refs.form
        const form = cfrom.$refs.cForm.$refs.form
        form.validate(() => {})
      })
    },
    handleBeforeSave(model) {
      model.main_business = this.provinceMainBusinessEnum[model.main_business_code]

      if (this.isBackData) {
        this.$emit('back', model)
        return
      }
      this.editData = { ...model }

      this.loading = true
      this.onSubmit()
    },
    handleDismiss() {
      this.$emit('update:visible', false)
    },
  },
}
</script>
<style lang="scss" scoped>
.project-new-form {
  .validate-result {
    display: none;
  }
  .is-success {
    .validate-result {
      display: inline-block;
      .fa-times {
        display: none;
      }
    }
  }
  .is-error {
    .validate-result {
      display: inline-block;
      .fa-check {
        display: none;
      }
    }
  }
}
</style>
